<?php

	session_start();
	if(!($_SESSION["username"])||($_SESSION["role"]!="TUT")){
		//not logged in or tutor
		header("location:index.php");
	}

	$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
	$objDB = mysql_select_db("Project 5.5");
	$strSQL = "SELECT * FROM groups";
	$objQuery = mysql_query($strSQL);
	if($objQuery){
		//*** Get Document Path ***//
		$strPath = realpath(basename(getenv($_SERVER["SCRIPT_NAME"])))."/temp";

		//*** Excel Document Root ***//
		$filename = "Groups_" . date('d-m-Y') . ".xls";

		//*** Connect to Excel.Application ***//
		$xlApp = new COM("Excel.Application");
		$xlBook = $xlApp->Workbooks->Add();

		//*** Create Sheet 1 ***//
		$xlBook->Worksheets(1)->Select;

		//*** Width & Height (A1:A1) ***//
		$xlApp->ActiveSheet->Range("A1:A1")->ColumnWidth = 9.0;
		$xlApp->ActiveSheet->Range("B1:B1")->ColumnWidth = 14.0;
		$xlApp->ActiveSheet->Range("C1:C1")->ColumnWidth = 44.0;
		$xlApp->ActiveSheet->Range("A1:G1")->HorizontalAlignment = -4108;

		//*** Header ***//
		$xlApp->ActiveSheet->Cells(1,1)->Value = "Group_ID";
		$xlApp->ActiveSheet->Cells(1,1)->Font->Bold = True;

		$xlApp->ActiveSheet->Cells(1,2)->Value = "Group_Name";
		$xlApp->ActiveSheet->Cells(1,2)->Font->Bold = True;

		$xlApp->ActiveSheet->Cells(1,3)->Value = "Group_Members";
		$xlApp->ActiveSheet->Cells(1,3)->Font->Bold = True;


		//***********//

		$intRows = 2;
		while($objResult = mysql_fetch_array($objQuery)){

			//*** Detail ***//
			$xlApp->ActiveSheet->Cells($intRows,1)->Value = $objResult["Group_ID"];
			$xlApp->ActiveSheet->Cells($intRows,1)->HorizontalAlignment = -4131; 
			$xlApp->ActiveSheet->Cells($intRows,2)->Value = $objResult["Group_Name"];
			$xlApp->ActiveSheet->Cells($intRows,2)->HorizontalAlignment = -4131; 
			
			$xlApp->ActiveSheet->Cells($intRows,3)->HorizontalAlignment = -4131; 
			$xlApp->ActiveSheet->Cells($intRows,3)->NumberFormat = "@";
			$xlApp->ActiveSheet->Cells($intRows,3)->Value = $objResult["Group_Members"];

			$intRows++;
		}

		@unlink("./temp/".$filename); //*** Delete old file ***//

		$xlBook->SaveAs($strPath."/".$filename); //*** Save to Path ***//

		header("Content-Disposition: attachment; filename=\".$filename\"");
		header("Content-Type: application/vnd.ms-excel");
		readfile('temp/'.$filename);


		//*** Close & Quit ***//
		$xlApp->Application->Quit();
		$xlApp = null;
		$xlBook = null;
		$xlSheet1 = null;

		@unlink("./temp/".$filename); //*** Delete new file ***//

	}

	mysql_close($objConnect);
?>
